#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Create by zhang
# Create on 2022/7/26 17:57
import re

from infrastructure.rules.validators.validator_interface import ValidatorInterface, ValidatorModeEnum
from infrastructure.utils.result_wrap import ResponseWrapper


class StrLengthValidator(ValidatorInterface):
    def __init__(self, length:int):
        super(StrLengthValidator, self).__init__()
        assert isinstance(length, int) and length > 0
        self.mode = ValidatorModeEnum.ENTITY
        self.length:int = length

    def validator__(self, value) -> ResponseWrapper:
        value = value if value is not None else ""
        if not isinstance(value, str):
            value = str(value)
        if value is None or len(value) == 0:
            return ResponseWrapper.fail(msg="字符串不能为空")
        if len(value) != self.length:
            return ResponseWrapper.fail(msg=f"字符串必须是{self.length}个字符")
        return ResponseWrapper.success()


class StrContentValidator(ValidatorInterface):
    def __init__(self, white_chars:str):
        super(StrContentValidator, self).__init__()
        assert isinstance(white_chars, str) and len(white_chars) > 0
        self.white_chars = white_chars
        self.mode = ValidatorModeEnum.ALL
        self.pattern = f"[^{white_chars}]+"

    def validator__(self, value) -> ResponseWrapper:
        value = value if value is not None else ""
        if not isinstance(value, str):
            value = str(value)
        result = re.search(self.pattern, value, flags=0)
        if result is not None:
            return ResponseWrapper.fail(msg=f"字符串中字符必须为【{self.white_chars}】中的字符")
        return ResponseWrapper.success()

